package edu.scau.mis.web.controller.pos;

import edu.scau.mis.core.domain.AjaxResult;
import edu.scau.mis.pos.domain.Order;
import edu.scau.mis.pos.domain.OrderItem;
import edu.scau.mis.pos.domain.Payment;
import edu.scau.mis.pos.domain.Product;
import edu.scau.mis.pos.mapper.OrderItemMapper;
import edu.scau.mis.pos.mapper.OrderMapper;
import edu.scau.mis.pos.mapper.PaymentMapper;
import edu.scau.mis.pos.mapper.ProductMapper;
import edu.scau.mis.pos.service.IOrderItemService;
import edu.scau.mis.pos.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;


@RestController
@RequestMapping("api/orders")
public class OrderController {

    @Resource
    private IOrderService orderService;
    @Autowired
    private IOrderItemService orderItemService;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private PaymentMapper paymentMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ProductMapper productMapper;

    // 查询订单列表（带分页）
    @GetMapping("/list")
    public List<Order> listOrders(
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) String payType,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        return orderService.listOrders(orderId, payType, startTime, endTime, status, pageNum, pageSize);
    }

    // 查询订单数量（分页需要）
    @GetMapping("/count")
    public int countOrders(
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) String payType,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Integer status
    ) {
        return orderService.countOrders(orderId, payType, startTime, endTime, status);
    }

    // 根据订单号查看订单基本信息
    @GetMapping("/{orderId}")
    public Order getOrder(@PathVariable String orderId) {
        return orderService.getOrderById(orderId);
    }

    // 根据订单号查看订单明细项
    @GetMapping("/{orderId}/items")
    public List<OrderItem> getOrderItems(@PathVariable String orderId) {
        return orderService.getOrderItemsByOrderId(orderId);
    }

    // 编辑订单（修改所有订单字段）
    @PostMapping("/edit")
    public AjaxResult editOrder(@RequestBody Order order) {
        // 1️⃣ 先检查传入的 Order 是否包含主键 orderId
        if (order.getOrderId() == null || order.getOrderId().isEmpty()) {
            return AjaxResult.error("订单编号不能为空");
        }

        // 2️⃣ 执行更新操作
        int result = orderService.updateOrder(order);

        // 3️⃣ 根据执行结果返回响应
        return result > 0 ? AjaxResult.success("编辑成功") : AjaxResult.error("编辑失败");
    }


    // 删除单个订单
    @DeleteMapping("/delete/{orderId}")
    public AjaxResult deleteOrder(@PathVariable String orderId) {
        int result = orderService.deleteOrder(orderId);
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败，请检查订单ID是否正确");
    }

    // 批量删除订单
    @PostMapping("/deleteBatch")
    public AjaxResult deleteOrders(@RequestBody List<String> orderIds) {
        int result = orderService.deleteOrders(orderIds);
        return result > 0 ? AjaxResult.success("批量删除成功") : AjaxResult.error("批量删除失败，请检查订单ID是否正确");
    }

    // 退货
    @PostMapping("/refund/{orderId}")
    public AjaxResult refundOrder(@PathVariable String orderId) {
        int result = orderService.refundOrder(orderId);
        return result > 0 ? AjaxResult.success("退货成功") : AjaxResult.error("退货失败，请检查订单ID是否正确");
    }

    // 换货
    @PostMapping("/order/change")
    public ResponseEntity<?> changeOrder(@RequestParam String orderId) {
        orderService.changeOrder(orderId);
        return ResponseEntity.ok("换货操作成功");
    }

    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody Order order) {
        if (order.getOrderId() == null || order.getOrderId().isEmpty()) {
            return AjaxResult.error("Order ID 不能为空");
        }
        boolean success = orderService.createOrder(order);
        return success ? AjaxResult.success() : AjaxResult.error("订单创建失败");
    }



    //接口3：根据商品SKU编码，获取该编码所对应的数据
    @GetMapping("/order/item-info")
    public AjaxResult getOrderItemInfo(@RequestParam String skuCode) {
        OrderItem item = orderService.getOrderItemInfoBySkuCode(skuCode);
        if (item != null) {
            // 构建简化后的数据对象
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("productSn", item.getProductSn());
            responseData.put("productName", item.getProductName());
            responseData.put("skuCode", item.getSkuCode());
            responseData.put("skuUrl", item.getSkuUrl());
            responseData.put("price", item.getPrice());


            return AjaxResult.success(responseData);
        } else {
            return AjaxResult.error("未找到商品");
        }
    }


    // 保存订单明细
    @PostMapping("/order/items")
    public AjaxResult saveOrderItems(@RequestParam String orderId, @RequestBody List<OrderItem> items) {

        // 🔹 第一步：检查 orderId 是否已存在
        if (orderService.getOrderById(orderId) == null) {
            // 如果 orderId 不存在，则先插入订单表
            Order order = new Order();
            order.setOrderId(orderId); // 只插入 orderId
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());

            // 👇 使用 orderMapper 插入
            int rows = orderMapper.insert(order);

            if (rows <= 0) {
                return AjaxResult.error("保存订单失败");
            }
        }

        // 🔹 第二步：保存订单明细
        int rows = orderService.saveOrderItems(orderId, items);

        if (rows > 0) {
            // 构建返回数据，包含自动生成的 orderItemId
            List<Map<String, Object>> responseData = new ArrayList<>();
            for (OrderItem item : items) {
                Map<String, Object> data = new HashMap<>();
                data.put("orderItemId", item.getOrderItemId());
                data.put("productSn", item.getProductSn());
                data.put("productName", item.getProductName());
                data.put("skuCode", item.getSkuCode());
                data.put("skuUrl", item.getSkuUrl());
                data.put("price", item.getPrice());
                data.put("quantity", item.getQuantity());
                data.put("amount", item.getAmount());
                responseData.add(data);
            }
            return AjaxResult.success(responseData);
        } else {
            return AjaxResult.error("保存订单明细失败");
        }
    }

    // 接口6：删除订单明细(用orderItemId删除)
    @DeleteMapping("/order-items/{orderItemId}")
    public AjaxResult deleteOrderItem(@PathVariable Long orderItemId) {
        int result = orderItemService.deleteOrderItemById(orderItemId);
        if (result > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    // 11：更新订单明细
    @PutMapping("/order-items")
    public AjaxResult updateOrderItem(@RequestBody OrderItem orderItem) {
        int result = orderItemService.updateOrderItem(orderItem);
        if (result > 0) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("修改失败");
        }
    }


    //接口8：挂单
    @PostMapping("/hang")
    public AjaxResult hangOrder(@RequestParam String orderId,
                                @RequestParam String payType,
                                @RequestParam Double amount) {  // 原价总金额

        // 1️⃣ 自动查询订单明细
        List<OrderItem> items = orderItemMapper.selectOrderItemsByOrderId(orderId);
        if (items == null || items.isEmpty()) {
            return AjaxResult.error("订单明细不存在，无法挂单");
        }

        // 2️⃣ 执行订单处理逻辑，状态为挂单（0 = 待支付）
        boolean success = orderService.processOrder(orderId, payType, amount, items, 0);

        return success ? AjaxResult.success("挂单成功") : AjaxResult.error("挂单失败");
    }



    //接口10：取消订单
    @DeleteMapping("/order-items/clear/{orderId}")
    public AjaxResult clearOrderItems(@PathVariable String orderId) {
        boolean success = orderService.clearOrderItems(orderId);
        return success ? AjaxResult.success("订单明细已清空") : AjaxResult.error("清空失败");
    }

    // 付款（只支持现金支付，金额 <= 0 则视为失败）
    @PostMapping("/pay")
    public AjaxResult simulatePayment(@RequestParam String orderId,
                                      @RequestParam String payType,
                                      @RequestParam Double amount) {

        // 1️⃣ 校验金额是否有效
        if (amount == null || amount <= 0) {
            String paymentId = "PY" + System.currentTimeMillis();
            Payment failedPayment = new Payment();
            failedPayment.setPaymentId(paymentId);
            failedPayment.setOrderId(orderId);
            failedPayment.setAmount(amount);
            failedPayment.setPayType(payType);
            failedPayment.setPayStatus("FAILED");
            failedPayment.setPaymentTime(new Date());
            failedPayment.setCreatedTime(new Date());
            failedPayment.setUpdatedTime(new Date());

            paymentMapper.insertPayment(failedPayment);
            return AjaxResult.error("支付失败：支付金额必须大于 0");
        }

        // 2️⃣ 校验支付方式（只支持现金）
        if (!"现金".equals(payType)) {
            return AjaxResult.error("只支持现金支付");
        }

        // 3️⃣ 查询订单明细
        List<OrderItem> items = orderItemMapper.selectOrderItemsByOrderId(orderId);
        if (items == null || items.isEmpty()) {
            return AjaxResult.error("订单明细不存在，无法付款");
        }

        // 4️⃣ 走订单处理逻辑，不再需要 totalAmount 和 totalQuantity
        boolean success = orderService.processOrder(orderId, payType, amount, items, 1);

        if (success) {
            // 更新库存和销量
            for (OrderItem item : items) {
                 int result1 = productMapper.decreaseStockQuantity(item.getSkuCode(), item.getQuantity());
                int result2 = productMapper.increaseSalesAndDecreaseStock(item.getProductSn(), item.getQuantity());
                System.out.println("decreaseStockQuantity affected rows: " + result1);
                System.out.println("increaseSalesAndDecreaseStock affected rows: " + result2);
            }
            String paymentId = "PY" + System.currentTimeMillis();
            Payment payment = new Payment();
            payment.setPaymentId(paymentId);
            payment.setOrderId(orderId);
            payment.setAmount(amount);
            payment.setPayType(payType);
            payment.setPayStatus("SUCCESS");
            payment.setPaymentTime(new Date());
            payment.setCreatedTime(new Date());
            payment.setUpdatedTime(new Date());

            paymentMapper.insertPayment(payment);
            return AjaxResult.success("支付成功");
        } else {
            return AjaxResult.error("订单处理失败，无法完成支付");
        }
    }





}
